package com.sky.controller.user;

import com.sky.constant.StatusConstant;
import com.sky.entity.Dish;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Slf4j
@RestController(value = "userDishController")
@RequestMapping(value = "/user/dish")
@Api(tags = "用户端 - 菜品浏览接口")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;

    /*根据分类id查询菜品*/
    @GetMapping(value = "/list")
    public Result<List<DishVO>> list(Long categoryId) {
        log.info("根据分类id查询菜品,{}", categoryId);
        // 1.构造redis中的key，key = "dish_" + categoryId;
        String key = "dish_" + categoryId;
        // 2.查询redis中是否存在此key
        List<DishVO> list = (List<DishVO>) redisTemplate.opsForValue().get(key); // 强制类型转换成存入redis时，java中的数据类型
        if (list != null) {
            return Result.success(list);
        }
        // 3.redis中没有缓存当前分类菜品数据就去数据库查询
        log.info("redis缓存中没有此{}分类菜品数据", key);
        Dish dish = new Dish();
        dish.setCategoryId(categoryId);
        dish.setStatus(StatusConstant.ENABLE); //查询起售中的商品
        list = dishService.listWithFlavor(dish);
        // 4.查询到数据后，将数据存入redis
        redisTemplate.opsForValue().set(key, list);
        return Result.success(list);
    }
}
